const { mouse } = require('@nut-tree-fork/nut-js');
const path = require('path');
const fs = require('fs');

// ===== 配置文件管理 =====
const CONFIG_FILE = path.join(__dirname, 'config.json');

// 读取配置文件
function loadConfig() {
    try {
        if (fs.existsSync(CONFIG_FILE)) {
            const configData = fs.readFileSync(CONFIG_FILE, 'utf8');
            const config = JSON.parse(configData);
            return { ...config };
        } else {
            console.log('📁 配置文件不存在！');
        }
    } catch (error) {
        console.log('⚠️ 配置文件读取失败！', error.message);
    }
}

// 保存配置文件
function saveConfig(config) {
    try {
        fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8');
        console.log('💾 配置文件已保存');
        return true;
    } catch (error) {
        console.error('❌ 配置文件保存失败:', error.message);
        return false;
    }
}

// 确保配置项默认值
function ensureConfigDefaults(config) {
    const safe = config && typeof config === 'object' ? { ...config } : {};
    if (!safe.coordinateOffset) {
        safe.coordinateOffset = { offsetX: 0, offsetY: 0 };
    } else {
        if (typeof safe.coordinateOffset.offsetX !== 'number') safe.coordinateOffset.offsetX = 0;
        if (typeof safe.coordinateOffset.offsetY !== 'number') safe.coordinateOffset.offsetY = 0;
    }
    if (!safe.displayConfig) {
        safe.displayConfig = { primaryWidth: 1920, primaryHeight: 1080, isMultiDisplay: false };
    } else {
        if (typeof safe.displayConfig.primaryWidth !== 'number') safe.displayConfig.primaryWidth = 1920;
        if (typeof safe.displayConfig.primaryHeight !== 'number') safe.displayConfig.primaryHeight = 1080;
        if (typeof safe.displayConfig.isMultiDisplay !== 'boolean') safe.displayConfig.isMultiDisplay = false;
    }
    if (!safe.fineTune) {
        safe.fineTune = { enableFineTune: true, stepSize: 20, maxOffset: 1000 };
    } else {
        if (typeof safe.fineTune.enableFineTune !== 'boolean') safe.fineTune.enableFineTune = true;
        if (typeof safe.fineTune.stepSize !== 'number') safe.fineTune.stepSize = 20;
        if (typeof safe.fineTune.maxOffset !== 'number') safe.fineTune.maxOffset = 1000;
    }
    // 新增：批量点击录制点
    if (!Array.isArray(safe.clickPoints)) {
        safe.clickPoints = [];
    }
    return safe;
}

// 加载配置
let CONFIG = ensureConfigDefaults(loadConfig());
if (!CONFIG) {
    CONFIG = ensureConfigDefaults({});
    saveConfig(CONFIG);
}

// ===== 用户配置区域 =====
// 如果点击位置不准确，请调整以下偏移值
const COORDINATE_OFFSET = CONFIG.coordinateOffset;

// ===== 录制与批量点击 =====
const readline = require('readline');

function prompt(question) {
    return new Promise((resolve) => {
        const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
        rl.question(question, (answer) => {
            rl.close();
            resolve(answer);
        });
    });
}

async function recordPointsInteractive() {
    console.log('操作说明:');
    console.log('  - R: 记录当前鼠标位置');
    console.log('  - 回车键: 完成录制并保存');

    const points = [];
    readline.emitKeypressEvents(process.stdin);
    if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
        try { process.stdin.setRawMode(true); } catch (_) {}
    }
    // 确保 stdin 进入读取状态，避免在某些终端中直接退出
    if (typeof process.stdin.resume === 'function') {
        process.stdin.resume();
    }



    return new Promise((resolve) => {
        const onKey = async (str, key) => {
            const k = (key && key.name ? key.name : str).toLowerCase();
            if (k === 'r') {
                const pos = await mouse.getPosition();
                // 录制时反向扣除当前全局偏移，确保后续回放再加偏移能回到录制位置
                const rawX = pos.x - (COORDINATE_OFFSET.offsetX || 0);
                const rawY = pos.y - (COORDINATE_OFFSET.offsetY || 0);
                points.push({ x: rawX, y: rawY });
                console.log(`✅ 已记录: 实际(${pos.x}, ${pos.y}) -> 存储(${rawX}, ${rawY})，总计 ${points.length} 个`);

            } else if (k === 's' || k === 'q' || (key && key.sequence === '\r')) {
                // 保存
                const newConfig = ensureConfigDefaults(loadConfig() || CONFIG);
                newConfig.clickPoints = points;
                if (saveConfig(newConfig)) {
                    CONFIG = newConfig;
                    console.log('💾 点位已保存到配置文件');
                }
                process.stdin.off('keypress', onKey);
                if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
                    try { process.stdin.setRawMode(false); } catch (_) {}
                }
                if (typeof process.stdin.pause === 'function') {
                    process.stdin.pause();
                }
                resolve(points);
            } else if (k === 'escape') {
                console.log('👋 已退出录制（未保存）');
                process.stdin.off('keypress', onKey);
                if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
                    try { process.stdin.setRawMode(false); } catch (_) {}
                }
                if (typeof process.stdin.pause === 'function') {
                    process.stdin.pause();
                }
                resolve(points);
            }
        };
        process.stdin.on('keypress', onKey);
        console.log('▶ 等待按键（R记录位置, 回车键完成录制, Esc退出）...');
    });
}





async function main() {
    console.log('🚀 启动录制程序');
    console.log('📋 当前偏移: ' +
        `X${COORDINATE_OFFSET.offsetX >= 0 ? '+' : ''}${COORDINATE_OFFSET.offsetX}, ` +
        `Y${COORDINATE_OFFSET.offsetY >= 0 ? '+' : ''}${COORDINATE_OFFSET.offsetY}`);

    // 开始录制
    const recordedPoints = await recordPointsInteractive();
    
    if (recordedPoints && recordedPoints.length > 0) {
        console.log(`\n✅ 录制完成！共记录 ${recordedPoints.length} 个坐标点`);
    } 
}

// 运行主程序
main();